<!-- src/views/system/stats/index.vue -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <!-- 地名指示牌数量统计查询 --> <!-- 维修情况统计查询 -->
      <el-row>
        <el-col :span="12">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>地名指示牌数量统计</span>
            </div>
            <el-form-item label="统计分类">
              <el-select v-model="countStatsType" placeholder="请选择统计分类" style="width: 200px" @change="handleCountStatsQuery">
                <el-option label="按所属街道统计" value="street" />
                <el-option label="按道路名称统计" value="road" />
              </el-select>
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>维修情况统计</span>
            </div>
            <el-form-item label="统计时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleMaintenanceStatsQuery">统计</el-button>
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
    </el-form>

    <!-- 地名指示牌数量统计结果 -->
    <el-row :gutter="20" style="margin-top: 20px;" v-if="countStatsData.length > 0">
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>地名指示牌数量分布图</span>
          </div>
          <div v-if="countStatsData.length > 0" ref="countChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>地名指示牌数量统计表</span>
          </div>
          <div style="overflow-y: auto;height: 400px;">
            <el-table :data="countStatsData" border  @row-dblclick="handleRowDblClick1">
              <el-table-column prop="name" label="分类" align="center" />
              <el-table-column prop="count" label="数量" align="center" />


<!--              按照街道统计-->
              <el-table-column prop="streetPoints" label="应设点位" align="center" v-if="countStatsType === 'street'">
                <template slot-scope="scope">
                  <span v-if="editingRow !== scope.$index">{{ scope.row.streetPoints }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.streetPoints"
                    size="mini"
                    @blur="handleBlur1(scope.row)"></el-input>
                </template>
              </el-table-column>
              <!--              oninput="value=value.replace(/[^0-9]/g,'')"-->
              <el-table-column prop="roadBoard" label="实有牌数" align="center" v-if="countStatsType === 'street'">
                <template slot-scope="scope">
                  <span v-if="editingRow !== scope.$index">{{ scope.row.roadBoard }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.roadBoard"
                    size="mini"
                    @blur="handleBlur1(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>


              <el-table-column prop="" label="差值" align="center" v-if="countStatsType === 'street'">
                <template slot-scope="scope">
                  {{
                    isNaN(scope.row.streetPoints - scope.row.roadBoard) ?
                      '' :
                      scope.row.streetPoints - scope.row.roadBoard
                  }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 维修情况汇总 -->
    <el-row :gutter="20" style="margin-top: 20px;" v-if="maintenanceSummary">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>维修情况汇总</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="4" v-for="item in summaryItems" :key="item.label">
              <div class="summary-item">
                <div class="summary-value">{{ item.value }}</div>
                <div class="summary-label">{{ item.label }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 维修情况统计结果 -->
    <el-row :gutter="20" style="margin-top: 20px;" v-if="maintenanceStatsData.length > 0">
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>维修费用TOP10</span>
          </div>
          <div v-if="maintenanceStatsData.length > 0" ref="costChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>维修情况统计表</span>
          </div>
          <div style="height: 380px;overflow-y: auto;">
            <el-table v-loading="loading" :data="maintenanceStatsData">
              <el-table-column label="地名指示牌名称" align="center" prop="roadName" />
              <el-table-column label="所属街道" align="center" prop="street" />
              <el-table-column label="维修次数" align="center" prop="maintenanceCount" />
              <el-table-column label="维修费用" align="center" prop="totalCost">
                <template slot-scope="scope">
                  <span>¥{{ scope.row.totalCost.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="最后维修日期" align="center" prop="lastMaintenanceDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.lastMaintenanceDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
            </el-table>

          </div>
          <div style="height: 20px;">
            <pagination
              v-show="maintenanceTotal>0"
              :total="maintenanceTotal"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getMaintenanceStats"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { getRoadSignCountStats, listMaintenanceStats, getMaintenanceSummary } from "@/api/road/stats";
import * as echarts from 'echarts';
import {addStreet, getStreetByStreetName, listStreet, updateStreet} from "@/api/statistics/sta-street";

export default {
  name: "RoadSignStats",
  watch:{
    countStatsData: {
      handler() {
        this.$nextTick(() => {
          if (this.countStatsData.length > 0) {
            this.renderCountChart();
          }
        });
      },
      deep: true
    },

    maintenanceStatsData: {
      handler() {
        this.$nextTick(() => {
          if (this.maintenanceStatsData.length > 0) {
            this.renderCostChart();
          }
        });
      },
      deep: true
    }
  },
  data() {
    return {

      originalRowData: undefined,
      editingRow: null,


      // 添加图表实例状态
      chartsInitialized: false,

      // 地名指示牌数量统计
      countStatsType: 'street',
      countStatsData: [],
      // 维修统计
      dateRange: [],
      maintenanceStatsData: [],
      maintenanceTotal: 0,
      maintenanceSummary: null,
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        statsType: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      // 图表实例
      countChart: null,
      costChart: null,
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  computed: {
    summaryItems() {
      if (!this.maintenanceSummary) return [];
      return [
        { label: '维修总次数', value: this.maintenanceSummary.totalMaintenanceCount },
        { label: '涉及地名指示牌数量', value: this.maintenanceSummary.maintainedSignCount },
        { label: '总维修费用', value: '¥' + (this.maintenanceSummary.totalCost?.toFixed(2) || '0.00') },
        { label: '平均维修费用', value: '¥' + (this.maintenanceSummary.avgMaintenanceCost?.toFixed(2) || '0.00') },
        { label: '最高维修费用', value: '¥' + (this.maintenanceSummary.maxMaintenanceCost?.toFixed(2) || '0.00') },
        { label: '最低维修费用', value: '¥' + (this.maintenanceSummary.minMaintenanceCost?.toFixed(2) || '0.00') }
      ];
    }
  },
  mounted() {
    // 初始化默认查询最近一个月的数据
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    this.dateRange = [this.parseTime(start, '{y}-{m}-{d}'), this.parseTime(end, '{y}-{m}-{d}')];

    // this.initCharts();
    this.handleCountStatsQuery();
    this.handleMaintenanceStatsQuery();

    // 修改初始化逻辑，使用 $nextTick

  },
  beforeDestroy() {
    if (this.countChart) {
      this.countChart.dispose();
    }
    if (this.costChart) {
      this.costChart.dispose();
    }
  },
  methods: {



    handleRowDblClick1(row, column, event) {
      this.editingRow = this.countStatsData.indexOf(row)

      // 记录原始值用于比较
      this.originalRowData = {
        streetPoints: row.streetPoints,
        roadBoard: row.roadBoard
      };
    },

    handleBlur1(val) {

      // 过滤非数字字符
      val.streetPoints = val.streetPoints ? val.streetPoints.toString().replace(/[^\d]/g, '') : '';
      val.roadBoard = val.roadBoard ? val.roadBoard.toString().replace(/[^\d]/g, '') : '';

      // 转换为数字（空字符串转为null）
      val.streetPoints = val.streetPoints ? parseInt(val.streetPoints) : null;
      val.roadBoard = val.roadBoard ? parseInt(val.roadBoard) : null;

      // 获取原始值
      const originalData = this.originalRowData;

      // 检查是否有实际变化
      const hasChanges =
        val.streetPoints !== originalData.streetPoints ||
        val.roadBoard !== originalData.roadBoard;

      // 检查是否两个字段都为空或null
      const bothEmpty =
        (!val.streetPoints || val.streetPoints === '') &&
        (!val.roadBoard || val.roadBoard === '');

      // 如果没有变化或两个字段都为空，则不执行操作
      if (!hasChanges || bothEmpty) {
        this.editingRow = null;
        console.log('无变化或字段为空，不执行操作');
        return;
      }

      this.editingRow = null
      console.log('blur val: ',val)
      console.log('blur name: ',val.name)


      /** 街道应设点位 */
      let streetPoints = val.streetPoints
      /** 街道实有牌数 */
      let roadBoard = val.roadBoard
      /** 关联的街道名称 */
      let streetName = val.name

      let data = {
        streetPoints,
        roadBoard,
        streetName
      }

      let id = null
      console.log('getStreetByStreetName streetName: ',streetName)
      // 根据街道名称查询
      getStreetByStreetName(streetName).then(res => {
        console.log('getStreetByStreetName res: ',res)
        // 查询到有结果返回，那就要修改
        if (res.hasOwnProperty('data')&&res.data.streetName === streetName){

              id = res.data.id
              // 更新 数据
              data = {id,...data}
              console.log('即将修改 data: ',data)
              updateStreet(data).then(res=>{
                console.log('updateStreet res: ',res)
                if (res.code === 200){
                  this.$message.success('更新成功！')
                }
              })


        // 否则就是新增
        }else {
          console.log('需要新增：')


          if(
            ((streetPoints!== null && streetPoints !== '')||
            (roadBoard!== null && roadBoard !== '')) && id === null
          ){
            // 新增
            addStreet(data).then(res => {
              if (res.code === 200){
                this.$message.success('添加成功！')
              }
            })
          }


        }
      })


    },

    /** 确保图表实例存在 */
    ensureCharts() {
      if (!this.chartsInitialized) {
        this.initCharts();
      }

      if (this.$refs.countChart && !this.countChart) {
        this.countChart = echarts.init(this.$refs.countChart);
      }
      if (this.$refs.costChart && !this.costChart) {
        this.costChart = echarts.init(this.$refs.costChart);
      }
    },

    /** 初始化图表 */
    initCharts() {
      // 添加DOM元素检查
      if (this.$refs.countChart) {
        this.countChart = echarts.init(this.$refs.countChart);
      }
      if (this.$refs.costChart) {
        this.costChart = echarts.init(this.$refs.costChart);
      }
      this.chartsInitialized = true;
    },

    /** 地名指示牌数量统计查询 */
    handleCountStatsQuery() {

      console.log(this.countStatsType)
      // 先保存当前的 streetPoints 和 roadBoard 数据
      const oldDataMap = {};
      this.countStatsData.forEach(item => {
        oldDataMap[item.name] = {
          streetPoints: item.streetPoints,
          roadBoard: item.roadBoard
        };
      });

      getRoadSignCountStats({ statsType: this.countStatsType }).then(response => {
        // 合并新旧数据
        const newData = response.data.map(item => {
          const oldData = oldDataMap[item.name];
          return {
            ...item,
            streetPoints: oldData ? oldData.streetPoints : null,
            roadBoard: oldData ? oldData.roadBoard : null
          };
        });
        this.countStatsData = newData;

        // 然后获取最新的街道数据
        return listStreet();
      }).then(res => {
        if (res && res.rows) {
          // 更新街道点位信息
          const updatedData = this.countStatsData.map(item => {
            const street = res.rows.find(row => row.streetName === item.name);
            if (street) {
              return {
                ...item,
                streetPoints: street.streetPoints,
                roadBoard: street.roadBoard
              };
            }
            return item;
          });
          this.countStatsData = updatedData;
        }

        this.$nextTick(() => {
          this.renderCountChart();
        });
      }).catch(error => {
        console.error('统计查询失败:', error);
      });
    },

    /** 维修情况统计查询 */
    handleMaintenanceStatsQuery() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0] + ' 00:00:00';
        this.queryParams.endTime = this.dateRange[1] + ' 23:59:59';
      }
      this.getMaintenanceStats();
      this.getMaintenanceSummary();
    },

    /** 获取维修统计列表 */
    getMaintenanceStats() {
      this.loading = true;
      listMaintenanceStats(this.queryParams).then(response => {
        this.maintenanceStatsData = response.rows;
        this.maintenanceTotal = response.total;
        this.loading = false;
        this.$nextTick(() => {
          this.renderCostChart();
        });
      });
    },

    /** 获取维修汇总 */
    getMaintenanceSummary() {
      getMaintenanceSummary(this.queryParams).then(response => {
        this.maintenanceSummary = response.data;
      });
    },

    /** 渲染地名指示牌数量统计图 */
    renderCountChart() {
      if (!this.countStatsData || this.countStatsData.length === 0) {
        return;
      }

      this.ensureCharts();

      if (!this.countChart) {
        console.error('Count chart instance is not available');
        return;
      }

      const option = {
        title: {
          text: '地名指示牌数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.countStatsData.map(item => item.name)
        },
        series: [
          {
            name: '地名指示牌数量',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.countStatsData.map(item => ({
              value: item.count,
              name: item.name
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      // this.countChart.setOption(option);

      try {
        this.countChart.setOption(option);
      } catch (error) {
        console.error('Error rendering count chart:', error);
      }
    },

    /** 渲染维修费用统计图 */
    renderCostChart() {
      if (!this.maintenanceStatsData || this.maintenanceStatsData.length === 0) {
        return;
      }

      this.ensureCharts();

      if (!this.costChart) {
        console.error('Cost chart instance is not available');
        return;
      }

      const top10Data = this.maintenanceStatsData.slice(0, 10);
      const option = {
        title: {
          text: '维修费用TOP10',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br/>维修费用: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: top10Data.map(item => item.roadName),
          axisLabel: {
            rotate: 45,
            interval: 0,
            textStyle: {
              fontSize: 10
            }
          },
          /*grid: {
            left: '3%',
            right: '4%',
            bottom: '15%', // 增加底部空间
            containLabel: true
          }*/
        },
        yAxis: {
          type: 'value',
          name: '费用(元)'
        },
        series: [
          {
            name: '维修费用',
            type: 'bar',
            data: top10Data.map(item => item.totalCost),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      };
      // this.costChart.setOption(option);

      try {
        this.costChart.setOption(option);
      } catch (error) {
        console.error('Error rendering cost chart:', error);
      }
    }
  }
};
</script>

<style scoped>
.summary-item {
  text-align: center;
  padding: 20px 0;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
}

.box-card {
  margin-bottom: 20px;
}
</style>
